import { reqCartList,reqDeleteCartById, reqUpdateCheckedById } from "@/api/api"


const shopcart = {
  namespaced: true,

  state:{
    cartList:[]
  },
  mutations:{
    GETCARTLIST(state,value){
      state.cartList = value
    }
  },
  actions:{
    // 获取购物车列表数据
   async getCartList(context) {
      let result = await reqCartList()
      if (result.code == 200) {
        context.commit('GETCARTLIST',result.data)
      }
      
    },
    // 删除购物车数据
    async deleteCartListBySkuId(context,skuId){
      let res = await reqDeleteCartById(skuId)
      if (res.code === 200) {
        return "ok"
      } else {
        return Promise.reject(new Error("faile"))
      }
    },
    
    // 修改商品选中状态
   async updateCheckedById(context,{skuId,isChecked}){
     let result = await reqUpdateCheckedById(skuId,isChecked)
     if (result === 200 ) {
        return "ok"
     } else {
      return Promise.reject(new Error("faile"))
     }
    },

    // 删除全部勾选的产品
    deleteAllCheckedCart(context){
       //
       context.getters.cartList.cartInfoList.forEach(element => {
        if (element.isChecked === 1) {
          context.dispatch('deleteCartListBySkuId',element.skuId)
        }
       });
    }
  },
  // 简化购物车数据
  getters:{
    cartList(state){
      return state.cartList[0] || {}
    }
  }

}

export default shopcart